<html lang="zh-cn">
<head>
    <meta charset="utf-8"/>
    <title><%= title %></title>
    <link rel="icon" href="favicon.ico"/>
    <link rel="stylesheet" href="css/main.css"/>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="js/socket.io-stream.js"></script>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/my/repo.data.js"></script>
    <script type="text/javascript">
    var socket = io();
    var bUpdatingTips = false;
    let lineBuffer = '';
    let bScroll = true;

    function openRepo(formId) {
        var customRepoEle = $('#customrepo1');
        if (formId == 'pastesome') {
            customRepoEle = $('#customrepo2');
        }
        var formEle = $('#' + formId);
        var t = formEle.serializeArray();
        var repoUrl = '';
        $.each(t, function () {
            if (this.name == 'repo') {
                if (this.value == 'custom') {
                    repoUrl = customRepoEle.val();
                } else {
                    repoUrl = this.value;
                }
            }
        });
        if (repoUrl != '') {
            window.open(repoUrl);
        }
    }

    function submitForm(formId, submitButtonId) {
        $('#tipsTable')[0] && ($('#tipsTable')[0].style.display = 'none');
        var customRepoEle = $('#customrepo1');
        if (formId == 'pastesome') {
            customRepoEle = $('#customrepo2');
        }
        var formEle = $('#' + formId);
        var btnEle = $('#' + submitButtonId);
        btnEle.disabled = 'disabled';
        btnEle.value = '正在提取，请稍等！';
        $('#msgcontainer').empty();
        $('#messages')[0].style.display = 'block';
        // formEle.submit();
        var d = {
            action: formEle.attr('action')
        };
        var t = formEle.serializeArray();
        $.each(t, function () {
            if (this.name in d) {
                d[this.name] = d[this.name] + ',' + this.value;
            } else {
                d[this.name] = this.value;
            }
            // 特殊处理：自定义仓库URL
            if (this.name == 'repo' && this.value == 'custom') {
                d['repo'] = customRepoEle.val();
            }
        });
        if (formEle.attr('action') == '/upload') {
            var file = $('#pomfile')[0].files[0];
            var stream = ss.createStream();
            ss(socket).emit('upload file', stream, {name: file.name, size: file.size});
            ss.createBlobReadStream(file).pipe(stream);
            d['file'] = {};
            d['file']['path'] = file.name;
        }
        socket.emit('add request', JSON.stringify(d));
        // alert(JSON.stringify(d));
    }

    socket.on('chat message', function (msg) {
        // appendMessage('[INFO]' + msg);
        appendMessage(msg);
    });

    socket.on('error message', function (msg) {
        appendMessage('[ERROR]' + msg);
    });

    function appendMessage(msg) {
        //console.log(msg);
        const changeLine = (msg[msg.length-1]=='\n');
        msg = msg.replace(/\r\n/g, '\n');
        var lines = msg.split('\n');
        if (lineBuffer.length > 0) {
            lines[0] = lineBuffer + lines[0];
            lineBuffer = '';
        }
        if (!changeLine) {
            lineBuffer = lines[lines.length-1];
            lines.splice(lines.length-1, 1);
        }
        lines.forEach(line => {
            if (line.indexOf('\r') >= 0) {
                var tmpblocks = line.split('\r');
                line = tmpblocks[tmpblocks.length-1];
            }
            if (line.substring(0, 8) == '[FINISH]' || line.substring(0, 10) == '[FINISH#2]') {
                if (line.substring(0, 8) == '[FINISH]') {
                    $('#msgcontainer').append('<a href="/download?id=' + line.substring(8) + '">下载结果文件（一小时内有效）</a>');
                } else {
                    $('#msgcontainer').append('<a href="/download?id=' + line.substring(10) + '">下载结果文件#2（一小时内有效）</a>');
                }
                $('#msgcontainer').append($('<div>').addClass('finishMsg').html('成功完成'));
             } else if (line.substring(0, 7) == '[ERROR]') {
                $('#msgcontainer').append($('<div>').addClass('errMsg').html(line));
            } else {
                $('#msgcontainer').append($('<div>').html(line));
            }
            if ($('#msgcontainer')[0].children.length > 2000) {
                $('#msgcontainer')[0].removeChild($('#msgcontainer')[0].children[0]);
            }
        });
        if (bScroll) {
            document.getElementById('msg_end').scrollIntoView();
        }
        // $('msg_end').focus();
    }

    function showMessages() {
        $('#messages')[0].style.display = 'block';
    }

    function clearMessages() {
        $('#messages')[0].style.display = 'none';
    }

    function showHelp() {
        var msg = '本工具用于快速从各大MAVEN仓库提取jar包和相关的依赖包（含pom文件），并自动同步到内网仓库中。<br/>' + 
            '如果知道需要的jar的groupId、artifactId和version信息，可以直接提取；否则，推荐您一个查找jar包的网站（<a href=\'https://mvnrepository.com/\' target=\'_blank\'>点这里</a>）。';
        var html = "<div class='closebtn'><a href='javascript:void(0)' onclick='clearHelp()'>[关闭]</a>&nbsp;&nbsp;&nbsp;&nbsp;</div>";
        $('body').append($('<div id="helpDiv">').html(html + msg));
    }

    function clearHelp() {
        $('#helpDiv').remove();
    }

    function clearComment(curObj) {
        if (bUpdatingTips) {
            return;
        }
        var curText = curObj.value;
        var newText = curText.replace(/<!--.+?-->/, '');

        bUpdatingTips = true;
        curObj.value = newText;
        bUpdatingTips = false;
    }

    function uniqueGAVArray(arr) {
        // 通过map实现基于GAV的合并
        const res = new Map();
        arr.forEach(a => {
            const gavStr = a['groupId'] + ':' + a['artifactId'] + ':' + a['version'];
            var cl = a['classifier'];
            var pk = a['packaging'];
            if (cl.length == 0) {
                cl = '(' + pk + ')';
            }
            if (!res.has(gavStr)) {
                var obj = {
                    'groupId': a['groupId'], 
                    'artifactId': a['artifactId'], 
                    'version': a['version'], 
                    'classifiers': cl
                };
                res.set(gavStr, obj);
            } else {
                res.get(gavStr)['classifiers'] += ',' + cl;
            }
        });
        // 从map的value提取出数组array
        const list = [];
        res.forEach(b => {
            list.push(b);
        });
        // 返回数组
        return list;
    }

    function getTips(curObj) {
        if (bUpdatingTips) {
            return;
        }
        if ($('#repos1').val() != 'default') {
            $('#tipsTable')[0] && ($('#tipsTable')[0].style.display = 'none');
            return;
        }
        var groupIdObj = $('#groupid');
        var artifactIdObj = $('#artifactid');
        var versionObj = $('#version');
        var curText = curObj.value;
        if (curText.length < 5 || (curObj.id == 'version' && curText.length == 0)) {
            return;
        }
        var groupIdStr = '';
        var artifactIdStr = '';
        var versionStr = '';
        if (groupIdObj.val().length >= 5) {
            groupIdStr = groupIdObj.val() + '*';
        }
        if (artifactIdObj.val().length >= 5) {
            artifactIdStr = artifactIdObj.val() + '*';
        }
        if (versionObj.val().length >= 1) {
            versionStr = versionObj.val() + '*';
        }
        var url = '/search/gav?_input_charset=utf-8&groupId=' + groupIdStr + '&repoId=central&artifactId=' + artifactIdStr + '&version=' + versionStr;
        $.ajax({
            url: url,
            dataType: 'json',
            success: function(jsonObj) {
                if (jsonObj.successful) {
                    var datas = jsonObj.object;
                    var uniqueDatas = [];
                    uniqueDatas = uniqueGAVArray(datas);
                    if (uniqueDatas.length > 0) {
                        if ($('#tipsTable').length > 0) {
                            $('#tipsTable').remove();
                        }
                        var tbodyEle = $('<tbody>').append($('<tr>')
                            .append($('<th>').text('GroupId'))
                            .append($('<th>').text('ArtifactId'))
                            .append($('<th>').text('Version'))
                            .append($('<th>').text('Classifiers'))
                            .append($('<th>').text('操作')));
                        var tableEle = $('<table id="tipsTable">').addClass('tipsTable').append(tbodyEle);
                        uniqueDatas.forEach(data => {
                            var trEle = $('<tr>');
                            trEle.append($('<td>').text(data.groupId));
                            trEle.append($('<td>').text(data.artifactId));
                            trEle.append($('<td>').text(data.version));
                            trEle.append($('<td>').text(data.classifiers));
                            trEle.append($('<td>').html('<a class="smlLnk" href="javascript:void(0)"' + 
                                ' onclick="writeGAV(\'' + data.groupId + '\',\'' + 
                                data.artifactId + '\',\'' + data.version + '\',\'' + 
                                data.classifiers + '\')">选中</a>'));
                            tbodyEle.append(trEle);
                        });
                        tableEle.css('left', curObj.getBoundingClientRect().right + 2);
                        tableEle.css('top', curObj.getBoundingClientRect().top);
                        $('body').append(tableEle);
                    }
                }
            }
        });
    }

    function writeGAV(groupId, artifactId, version, classifiers) {
        bUpdatingTips = true;
        $('#groupid').val(groupId);
        $('#artifactid').val(artifactId);
        $('#version').val(version);
        $('#tipsTable').remove();
        $('#restype0').click();
        if (classifiers == '(pom)') {
            $('#restype4').click();
        }
        $("input[name='classifier']").each(function(){this.checked=false;});
        $('#classifier1')[0].checked = true;
        var classifierArr = classifiers.split(',');
        classifierArr.forEach(c => {
            if (c == 'sources') {
                $('#classifier2')[0].checked = true;
            } else if (c == 'tests') {
                $('#classifier3')[0].checked = true;
            } else if (c == 'javadoc') {
                $('#classifier4')[0].checked = true;
            }
        });
        bUpdatingTips = false;
    }

    function initRepos(id) {
        var selectEle = $("#repos" + id);
        selectEle.append($('<option>').val('default').text('default'));
        repoArr.forEach(repoObj => {
            selectEle.append($('<option>').val(repoObj.url).text(repoObj.name));
        });
        selectEle.append($('<option>').val('custom').text('custom'));
    }

    function repoChange(id) {
        var selectEle = document.getElementById("repos" + id);
        var repoValue = selectEle.options[selectEle.selectedIndex].value;
        if (repoValue == "custom") {
            $('#customrepo' + id)[0].style.display = '';
        } else {
            $('#customrepo' + id)[0].style.display = 'none';
        }
        if (id == 1 && repoValue != 'default') {
            $('#classifier2')[0].checked = false;
            $('#classifier3')[0].checked = false;
            $('#classifier4')[0].checked = false;
        }
        if (repoValue == 'default') {
            $('#openRepoLink' + id)[0].style.display = 'none';
        } else {
            $('#openRepoLink' + id)[0].style.display = '';
        }
    }

    window.onload = function () {
        initRepos(1);
        initRepos(2);
        var defaultVal = '<dependency>\n' + 
            '    <groupId></groupId>\n' + 
            '    <artifactId></artifactId>\n' + 
            '    <version></version>\n' + 
            '</dependency>';
        $('#depcontent').val(defaultVal);
    }
    </script>
</head>
<body style="height: calc(100% - 16px)">
    <center>
    <h1>欢迎使用 <%= title %></h1>
    <br/>
    目前，有以下几种不同的提取方式，请根据自己的需要选择使用。&nbsp;&nbsp;<a class='smlLnk' href='javascript:void(0)' onclick='showHelp()'>帮助</a>
    <br/>
    <h3>1、上传pom.xml文件方式</h3>
    <div>
        <form id='editfile' method='post' action='/upload' enctype='multipart/form-data'>
            <table><tbody>
                <tr><td style="width:100px;">插件版本：</td><td style="width:660px;"><select name="plgver" id='plgver'><option value="3.3.0">3.3.0(新版)</option><option value="2.8">2.8(旧版)</option></select></td></tr>
                <tr><td>选择文件：</td><td><input name="pomfile" id='pomfile' type='file' /></td></tr>
                <tr><td colspan="2" style="text-align: center"><input type='button' id='submitFile' value='上传文件并开始提取' onclick="submitForm('editfile','submitFile')" /></td></tr>
            </tbody></table>
        </form>
    </div>
    <br/>
    <h3>2、指定单个包的信息提取方式</h3>
    <div>
        <form id='editsingle' method='post' action='/uploadsingle'>
            <table><tbody>
                <tr><td style="width:100px;">插件版本：</td><td style="width:660px;"><select name="plgver" id='plgver'><option value="3.3.0">3.3.0(新版)</option><option value="2.8">2.8(旧版)</option></select></td></tr>
                <tr>
                    <td>Repo：</td>
                    <td>
                        <select id="repos1" name="repo" onchange="repoChange(1)" multiple111="multiple"></select>
                        <input id='customrepo1' type='text' style="display: none; width: 400px" />
                        <a id="openRepoLink1" style="display: none;" href="javascript:void(0)" onclick="openRepo('editsingle')">浏览仓库</a>
                    </td>
                </tr>
                <tr><td>groupId：</td><td><input name="groupid" id='groupid' type='text' oninput="getTips(this)" /></td></tr>
                <tr><td>artifactId：</td><td><input name="artifactid" id='artifactid' type='text' oninput="getTips(this)" /></td></tr>
                <tr><td>version：</td><td><input name="version" id='version' type='text' oninput="getTips(this)" /></td></tr>
                <tr><td>type：</td><td>
                    <input name="restype" id='restype0' type='radio' value='any' checked='checked' /><label for='restype1'>(any)</label>&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="restype" id='restype1' type='radio' value='jar' /><label for='restype1'>jar</label>&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="restype" id='restype2' type='radio' value='test-jar' /><label for='restype2'>test-jar</label>&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="restype" id='restype3' type='radio' value='java-source' /><label for='restype3'>java-source</label>&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="restype" id='restype4' type='radio' value='pom' /><label for='restype4'>pom</label>&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="restype" id='restype5' type='radio' value='javadoc' /><label for='restype5'>javadoc</label>
                </td></tr>
                <tr><td>classifier：</td><td>
                    <input name="classifier" id='classifier1' type='checkbox' value='' checked='checked' /><label for='classifier1'>(none)</label>&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="classifier" id='classifier2' type='checkbox' value='sources' checked='checked' /><label for='classifier2'>sources</label>&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="classifier" id='classifier3' type='checkbox' value='tests' /><label for='classifier3'>tests</label>&nbsp;&nbsp;&nbsp;&nbsp;
                    <input name="classifier" id='classifier4' type='checkbox' value='javadoc' checked='checked' /><label for='classifier4'>javadoc</label><br/>
                    <input name="classifier" id='classifierOthers' type='checkbox' value='others' /><label for='classifierOthers'>Others:</label><input type="text" id='otherclassifiers' name='otherclassifiers' />
                </td></tr>
                <tr><td>变量：</td><td>
                    <input name="variables" id='variables' type='text' value='' placeholder='格式：key1=val1,key2=val2,...' />
                </td></tr>
                <tr><td colspan="2" style="text-align: center"><input type='button' id='submitSingle' value='开始提取' onclick="submitForm('editsingle','submitSingle')" /></td></tr>
            </tbody></table>
        </form>
    </div>
    <br/>
    <h3>3、粘贴一段pom中的依赖xml的提取方式</h3>
    <div>
        <form id='pastesome' method='post' action='/uploadsome'>
            <table><tbody>
                <tr><td style="width:100px;">插件版本：</td><td style="width:660px;"><select name="plgver" id='plgver'><option value="3.3.0">3.3.0(新版)</option><option value="2.8">2.8(旧版)</option></select></td></tr>
                <tr>
                    <td>Repo：</td>
                    <td>
                        <select id="repos2" name="repo" onchange="repoChange(2)"></select>
                        <input id='customrepo2' type='text' style="display: none; width: 400px" />
                        <a id="openRepoLink2" style="display: none;" href="javascript:void(0)" onclick="openRepo('pastesome')">浏览仓库</a>
                    </td>
                </tr>
                <tr><td>dependencies内容：</td><td><textarea name="depcontent" id='depcontent' cols="75" rows="8" oninput="clearComment(this)"></textarea></td></tr>
                <tr><td colspan="2" style="text-align: center"><input type='button' id='submitSome' value='开始提取' onclick="submitForm('pastesome','submitSome')" /></td></tr>
            </tbody></table>
        </form>
    </div>
    </center>
    <div id='messages'>
        <div class='closebtn'><input type='checkbox' id='autoScroll' checked='checked' onchange='bScroll=this.checked'/><label for='autoScroll'>自动滚屏</label>&nbsp;&nbsp;<a href="javascript:void(0)" onclick="clearMessages()">[关闭]</a>&nbsp;&nbsp;&nbsp;&nbsp;</div>
        <div id='msgcontainer'></div>
        <div id='msg_end'></div>
    </div>
    <div id='operatebar'><a href="javascript:void(0)" onclick="showMessages()">[显示maven导出进度信息]</a></div>
</body>
</html>
